package com.lei.session.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionFilter implements Filter {
	private Set<String> set = new HashSet<>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
		set.add("/s04session/login.jsp");
		set.add("/s04session/");
		set.add("/VerifyServlet");
		set.add("/UserServlet");
		set.add("/index.html");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		// 请求路径
		String path = httpRequest.getServletPath();
		if (set.contains(path)) {
			System.out.println("不做拦截PATH = " + path);
			// 走一下个过滤器
			chain.doFilter(request, response);
		} else {
			System.out.println("拦截PATH = " + path);
			// 没有登陆
			if (httpRequest.getSession().getAttribute("loginInfo") == null) {
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/s04session/login.jsp");
			} else {
				// 走一下个过滤器
				chain.doFilter(request, response);
			}
		}
	}
}
